package cc.angis.xiugallery;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.db.FavouriteImagesDBHelper;
import cc.angis.xiugallery.db.TableConstants;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;

@SuppressLint("NewApi") 
public class MainActivity2 extends SherlockFragmentActivity {
	
	protected static final Intent SERVICE_INTENT = new Intent();
//	static {
////		SERVICE_INTENT.setComponent(new ComponentName(
////				"im.keep",
////				"im.keep.service.MaxMessageService"));
//		SERVICE_INTENT.setComponent(new ComponentName(
//				"cc.angis.xiugallery",
//				"cc.angis.xiugallery.service.CommentService"));
//	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// set the Above View
		setContentView(R.layout.pager);
//		startService(SERVICE_INTENT);
		this.getSharedPreferences(GlobalConst.PREF_NAME, 0).edit().putInt(GlobalConst.PREF_CUR_INDEX, 0).commit();
		if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//            ft.replace(R.id.content, JBImageGridFragment.newInstance(GlobalConst.CAMERA_IMAGE_BUCKET_ID, GlobalConst.INTENT_GROUP_TYPE_GALLERY, GlobalConst.MenuType.MENU_TYPE_IMAGEDISPLAY), GlobalConst.TAG_FRAGMENT_FAVOURITE);
            ft.replace(R.id.content, new FavouriteGridFragment());
            ft.commit();
        }		
		
		ActionBar actionbar = this.getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		// set the Behind View
//		android.support.v4.app.FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
//		t.replace(R.id.frame, new SampleListFragment());
//		t.commit();

		sendBroadcast(new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://"  
                + Environment.getExternalStorageDirectory())));
		
		new ScanTask().execute();

	}
	
	public class PagerAdapter extends android.support.v4.app.FragmentPagerAdapter implements 
	ViewPager.OnPageChangeListener{

		private List<android.support.v4.app.Fragment> mFragments = new ArrayList<android.support.v4.app.Fragment>();
		private ViewPager mPager;

		public PagerAdapter(android.support.v4.app.FragmentManager fragmentManager, ViewPager vp) {
			super(fragmentManager);
			mPager = vp;
			mPager.setAdapter(this);
			mPager.setOnPageChangeListener(this);
		}
		
//		public void addTab(Fragment frag) {
//			mFragments.add(frag);
//			mActionBar.addTab(mActionBar.newTab().setTabListener(this).
//					setText("Tab "+mFragments.size()));
//		}
		
		@Override
		public android.support.v4.app.Fragment getItem(int position) {
			return mFragments.get(position);
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

//		@Override
//		public void onTabSelected(Tab tab, FragmentTransaction ft) {
//			mPager.setCurrentItem(tab.getPosition());
//		}
//
//		public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
//		public void onTabReselected(Tab tab, FragmentTransaction ft) { }
		public void onPageScrollStateChanged(int arg0) { }
		public void onPageScrolled(int arg0, float arg1, int arg2) { }

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			
		}

	}
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		 SubMenu sub = menu.addSubMenu("Theme");
//	        sub.add(0, R.style.Theme_Sherlock, 0, "Default");
//	        sub.add(0, R.style.Theme_Sherlock_Light, 0, "Light");
//	        sub.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0, "Light (Dark Action Bar)");
//	        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//	        return true;
//	}
	
	public class ScanTask extends AsyncTask<String, Void, Integer>{

		@Override
		protected Integer doInBackground(String... params) {
			FavouriteImagesDBHelper dbHelper = new FavouriteImagesDBHelper(getApplicationContext(), TableConstants.TABLE_FAVOURITE_IMAGES);
			List<Long> imgs;
			try{
				imgs = dbHelper.getAllFav();
				StringBuilder builder = new StringBuilder();
				if (imgs.size() > 0){
					for (Long id:imgs){
						builder.append("'").append(id).append("'").append(",");
					}
					Cursor cursor = MainActivity2.this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
							new String[]{MediaStore.Images.Media._ID}, "_id IN (" + builder.substring(0, builder.length()-1) + ")", null, null);
					if(cursor.moveToFirst()){
						do{
							imgs.remove(cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
						} while(cursor.moveToNext());
					}
					cursor.close();
					builder = new StringBuilder();
					if(imgs.size()>0){
						for (Long id:imgs){
							builder.append("'").append(id).append("'").append(",");
						}
						
						dbHelper.deleteIn(builder.substring(0, builder.length()-1));
					}
				}
			} catch(Exception e){
				e.printStackTrace();
			} finally{
				dbHelper.closeDB();
			}
			return null;
		}
		
	}

}
